package com.epalmpay.controller.apiweixin;


import com.alibaba.fastjson.JSONObject;
import com.epalmpay.commom.BaseController;
import com.epalmpay.entity.*;
import com.epalmpay.enumdef.ActivityEnum;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.mapper.BonusVerifyLogMapper;
import com.epalmpay.mapper.BonusVerifyRuleMapper;
import com.epalmpay.mapper.BonusVerifyShopMapper;
import com.epalmpay.mapper.ShopMapper;
import com.epalmpay.service.app.IAppNoticeService;
import com.epalmpay.service.group.IGroupService;
import com.epalmpay.service.machinewasher.IMachineWasherService;
import com.epalmpay.service.trade.ITradeService;
import com.epalmpay.status.Rescode;
import com.epalmpay.dto.terminalmanage.DeviceOutDTO;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.service.device.IDeviceService;
import com.epalmpay.service.jobservice.IProfitStatisService;
import com.epalmpay.service.member.IMemberService;
import com.epalmpay.service.weixin.IWxApiMemberService;
import com.epalmpay.service.weixin.IWxApiWalletService;
import com.epalmpay.service.weixin.IWxBaseService;
import com.epalmpay.service.weixin.impl.WxService;
import com.epalmpay.util.Const;
import com.epalmpay.util.PageData;
import com.epalmpay.util.Response;
import com.epalmpay.util.Tools;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;


/**
 * 
* 类名称：WxApiPayController.java
* 类描述： 微信 支付宝  台卡支付
* @author zsj 
* 创建时间：2017年7月4日
 */
@Controller
@RequestMapping(value="/api/pay")
public class WxApiPayController extends BaseController{
	
	@Resource
	private IWxApiWalletService wxApiWalletServiceService;
	@Autowired
    protected WxService wxService;
	@Autowired
    protected IWxBaseService wxBaseService;
	@Autowired
    protected IDeviceService deviceService;
	@Resource
	private IWxApiMemberService wxApiMemberService;
	@Resource
	private  IProfitStatisService profitStatisService;
//	@Autowired
//	private ITokenService tokenService;
	@Resource
	private  IMemberService memberService;

	@Resource
	private IGroupService groupService;

	@Resource
	private IAppNoticeService appNoticeService;

	@Resource
	private ShopMapper shopMapper;

	@Resource
	private ITradeService tradeService;

	@Resource
	private IMachineWasherService machineWasherService;

	@Resource
	private BonusVerifyRuleMapper bonusVerifyRuleMapper;

	@Resource
	private BonusVerifyLogMapper bonusVerifyLogMapper;

	@Resource
	private BonusVerifyShopMapper bonusVerifyShopMapper;
	/**
	 * @return
	 * @throws Exception
	 */
//	@RequestMapping(value = "/orderQueryNotify", method = {RequestMethod.GET,RequestMethod.POST} )
//	@ResponseBody
//	public Response orderQueryNotify() throws Exception{
//		
//		wxApiWalletServiceService.updateOrderQueryNotify("ORG20171212094805832831");
//		return null;
//		
//	}
	
	/**根据memberId 微信公众号支付充值
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/weixinpay", method = RequestMethod.POST)
	@ResponseBody
	public Response weixinpay(HttpServletRequest request,String memberId,String recharge_money,Integer recharge_type) throws Exception{
		logBefore(logger, "微信公众号支付充值");
		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("会员编号", memberId);
		resultMap.put("充值金额", recharge_money);
		resultMap.put("充值类型", String.valueOf(recharge_type));
		String nullParam=Response.checkNull(resultMap);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		try {
			Map<String, Object> map=wxApiWalletServiceService.updateWeixinPay(memberId,recharge_money,recharge_type,Tools.getIpAddr(request));
			if(map == null || map.size()==0){
				throw new ApplicationException(Rescode.FAIL,"未查询到记录");
			}

			return Response.getSuccess(map);
		}catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	
	
	/** 微信公众号服务商品购买
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/weixinpayConsumption", method = RequestMethod.POST)
	@ResponseBody
	public Response weixinpayConsumption(HttpServletRequest request,String memberId,String recharge_money,String orgOrderNum) throws Exception{
		logBefore(logger, "微信公众号服务商品购买");
		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("会员编号", memberId);
		resultMap.put("消费金额", recharge_money);
		String nullParam=Response.checkNull(resultMap);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		try {
			String notifyUrl = HOME_URL + "/payplat/callback/rechargeTkNotify";
			Response response=wxApiWalletServiceService.updateWeixinPayConsumption(memberId,recharge_money,Tools.getIpAddr(request),orgOrderNum,ROOT_HOME_URL,notifyUrl);
			return response;
		} catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	
	
	/**根据手机号查询会员优惠劵列表信息
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/couponList", method = {RequestMethod.GET,RequestMethod.POST} )
	@ResponseBody
	public Response couponList(String deskcardCode,String deskcardId,String phone,Integer tranAmt,Integer nooffertranAmt) throws Exception{
		logBefore(logger, "根据手机号查询会员优惠劵信息");
		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("台卡编号", deskcardCode);
		resultMap.put("台卡ID", deskcardId);
		resultMap.put("手机号码", phone);
		resultMap.put("订单总金额", tranAmt+"");
		String nullParam=Response.checkNull(resultMap);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		if(nooffertranAmt!=null&&nooffertranAmt>tranAmt){
			return Response.getError("不参与优惠金额不能大于总金额");
		}
		try {
			/**检查这个用户与这个门店的 是否未支付的订单**/
        	wxApiWalletServiceService.checkUserShopOrderStatus(phone,deskcardId,deskcardCode);
        	
        	
			Map<String, Object> map=wxApiWalletServiceService.couponList(deskcardCode, deskcardId, phone, tranAmt,nooffertranAmt);
			if(map == null || map.size()==0){
				throw new ApplicationException(Rescode.FAIL,"未查询到记录");
			}
			return Response.getSuccess(map);
		} catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	    
	
	/**根据手机号查询会员可用积分数量
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/bonus", method = {RequestMethod.GET,RequestMethod.POST} )
	@ResponseBody
	public Response bonus(String deskcardCode,String deskcardId,String phone,Integer tranAmt,Integer nooffertranAmt) throws Exception{
		logBefore(logger, "实际付款金额");
		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("台卡编号", deskcardCode);
		resultMap.put("台卡ID", deskcardId);
		resultMap.put("订单总金额", tranAmt+"");
	//	resultMap.put("手机号码", phone);
		String nullParam=Response.checkNull(resultMap);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		try {
			/**检查这个用户与这个门店的 是否未支付的订单**/
        	wxApiWalletServiceService.checkUserShopOrderStatus(phone,deskcardId,deskcardCode);
        	
        	
			Response response=wxApiWalletServiceService.selectBonus(deskcardCode, deskcardId, phone, tranAmt, nooffertranAmt);
			return response;
		} catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	 
	
	/**
	 * 实际付款金额
	 * @param deskcardCode 台卡编号
	 * @param deskcardId 台卡ID
	 * @param phone
	 * @param tranAmt  订单总金额
	 * @param nooffertranAmt 不参与优惠金额
	 * @param couponUserId  优惠券id
	 * @param bonusAmount   积分数量
	 * @return
	 * @throws Exception
	 *  
	 */
	 
	@RequestMapping(value = "/actualMoney", method = {RequestMethod.GET,RequestMethod.POST} )
	@ResponseBody
	public Response actualMoney(String deskcardCode,String deskcardId,String phone,Integer tranAmt,Integer nooffertranAmt,
			String couponCodes,Integer bonusAmount) throws Exception{
		logBefore(logger, "实际付款金额");
		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("台卡编号", deskcardCode);
		resultMap.put("台卡ID", deskcardId);
		resultMap.put("订单总金额", tranAmt+"");
		resultMap.put("手机号码", phone);
		String nullParam=Response.checkNull(resultMap);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		//手机号码为空 直接返回 订单总金额
		if(Tools.isEmpty(phone)){ 
			return Response.getSuccess(tranAmt);
		}
		if(Tools.isEmpty(couponCodes)&&bonusAmount==null){ 
			return Response.getSuccess(tranAmt);
		}
		try {
			Response response=wxApiWalletServiceService.calActualMoney(deskcardCode, deskcardId, phone, tranAmt, nooffertranAmt, couponCodes, bonusAmount);
			return response;
		} catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	
	
	/**
	 * 授权首页
	 * @param deskcardCode  台卡编号
	 * @param deskcardId    主键ID
	 * @param request   
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tkIndex", method = {RequestMethod.GET,RequestMethod.POST} )
	public String tkIndex(String deskcardCode,String deskcardId,String fyMerchantId,String businessCode,
			HttpServletRequest request, HttpServletResponse response, Model model) throws Exception{
		logBefore(logger, "台卡授权首页"+HOME_URL);
		logBefore(logger, "台卡授权首页"+ROOT_HOME_URL);
		String type = request.getHeader("user-agent");
		
		if(StringUtils.isBlank(deskcardCode)||StringUtils.isBlank(deskcardId)){
			deskcardId=fyMerchantId;
			deskcardCode= businessCode;
		}
		
		if(StringUtils.isBlank(deskcardCode)||StringUtils.isBlank(deskcardId)){
			model.addAttribute("msg", "台卡参数错误，请联系系统管理员");
			return "payError";
		}
		DeviceOutDTO device=deviceService.getDeviceGroupId(deskcardCode, Long.valueOf(deskcardId)); 
		if(!Rescode.SUCCESS.equals(device.getErrorCode())){
			 model.addAttribute("msg", device.getErrorMsg());
			 return "payError";
		 }
		Long groupId=device.getGroupId();
		WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage=null;
		try {
			wxMpInMemoryConfigStorage = wxBaseService.getTokenByGroupId(groupId);
		} catch (Exception e1) {
			e1.printStackTrace();
			model.addAttribute("msg", "请用应用APP进行扫描");
			return "payError";
		}	
		try {
			if (type.toLowerCase().indexOf("micromessenger") >= 0) {
				//判断当前台卡对应的 门店是否 处于预采购状态
				logger.info(">>>>>>>>>门店名称>>>>"+device.getMerchantName());
				String name = java.net.URLEncoder.encode(device.getMerchantName(),"utf-8");
				logger.info(">>>>>>>>门店名称>>>>name>>>"+name);
				String  url=HOME_URL+"/api/pay/tkWxPayIndex"; 		
				 wxService.setWxMpConfigStorage(wxMpInMemoryConfigStorage);				
				 String href = wxService.oauth2buildAuthorizationUrl(
						 url+"?deskcardCode="+deskcardCode+"&deskcardId="+deskcardId+"&shopId="+device.getShopId()+"&groupId="+groupId+"&merchantName="+name,
					      WxConsts.OAUTH2_SCOPE_BASE, "");
				 logBefore(logger, "------------------------------------获取微信openId第1步结束-----------------------------------");
				 response.sendRedirect(href);
				 return null;
			}else 
			if (type.toLowerCase().indexOf("alipayclient") >= 0) {
				// 支付宝
				String url=HOME_URL+"/api/pay/tkAliPayIndex";
				logger.info(">>>>>>>>支付宝门店名称>>>>"+device.getMerchantName());
				 String name = java.net.URLEncoder.encode(device.getMerchantName(),"utf-8");
				logger.info(">>>>>>>>支付宝门店名称>>>>name>>>"+name);
				String path = url+"?deskcardCode="+deskcardCode+"&deskcardId="+deskcardId+"&shopId="+device.getShopId()+"&merchantName="+name;
				logBefore(logger, "支付宝授权url"+path);
				try {
					response.sendRedirect(path);
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "商户参数配置错误，请联系系统管理员");
			return "payError";
		}
		// 请用微信或者支付宝扫描
		logBefore(logger, "----------------非微信或支付宝扫描---------------------");
		model.addAttribute("msg", "请用微信或者支付宝扫描");
		return "payError";
	}
	
	
	
	/**
	 * 重定向至微信页 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tkWxPayIndex",method = {RequestMethod.GET,RequestMethod.POST} )
	public String tkWxPayIndex(HttpServletRequest request, HttpServletResponse response) throws Exception{
		 logBefore(logger, "微信第二步授权开始");
		 PageData pd = new PageData();
		 pd = this.getPageData();
		 String groupId=pd.getString("groupId");
		 String code=pd.getString("code"); 

		 String shopId = pd.getString("shopId");
		 String deskcardCode=pd.getString("deskcardCode");//编号
		 String deskcardId=pd.getString("deskcardId");//商户号
		 String merchantName=pd.getString("merchantName");
		 String name = java.net.URLEncoder.encode(merchantName,"utf-8");
		logger.info(">>>>>>>>>tkWxPayIndex 门店名称>>>>"+name);
//		URLDecoder.decode()
		 wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(Long.parseLong(groupId)));
		 WxMpOAuth2AccessToken wxMpOAuth2AccessToken = this.wxService.oauth2getAccessToken(code);  
		 String openId=wxMpOAuth2AccessToken.getOpenId();
		 String sign = new SimpleHash("SHA-1", deskcardCode, deskcardId).toString();
		 PrePurchaseActivity prePurchaseActivity= wxApiWalletServiceService.findPrePurchaseActivity(deskcardCode, deskcardId);
		 String url=null;		
		 if(prePurchaseActivity!=null){
			 url=String.format("%s/pay/recharge/wx_pay_yunliu.html?discount=%d&",ROOT_HOME_URL,prePurchaseActivity.getCustomerBenefitAmount());
		 }else{
			 //此处根据不同的支付类型跳转到不同的路径   迅联支付和新大陆支付 直接给支付地址           
			 DeviceDeskCard deviceDeskCard=deviceService.getDeviceDeskCardId(Long.valueOf(deskcardId));
			 
			 if(deviceDeskCard.getDeskcardOrganization()==(byte)BizEnum.DeskCardInNetCompany.fuqianla.getType()){
				 url=String.format("%s/pay/recharge/wx_pay.html?",ROOT_HOME_URL);
			 }else if(deviceDeskCard.getDeskcardOrganization()==(byte)BizEnum.DeskCardInNetCompany.xunlina.getType()){
				 url=String.format("%s/pay/recharge/wx_pay_jpy.html?",ROOT_HOME_URL);
			 }else if(deviceDeskCard.getDeskcardOrganization()==(byte)BizEnum.DeskCardInNetCompany.xindalu.getType()){
				 url=String.format("%s/pay/recharge/wx_pay_jpy.html?",ROOT_HOME_URL);
			 }
			 
		 }
		 //根据openId查询会员ID
		 url=url+"openId="+openId+"&deskcardCode="+deskcardCode+"&deskcardId="+deskcardId+"&sign="+sign+"&merchantName="+name+"&shopId="+shopId+"&random="+Math.random()*10000;
			
		  Member member=wxApiWalletServiceService.selectMemberInfo(Long.valueOf(groupId),null,openId);
		  if(member!=null){
			  url=url +"&phone="+member.getPhone()+"&memberId="+member.getId();
		  }else{
			  url=url +"&phone="+null+"&memberId="+null;
		  }

		logger.info(">>>>>>>url>>>>"+url);
		  logBefore(logger, "微信第二步授权结束");
		 response.sendRedirect(url);
		 return null; 
	}
	      
		
	  
	/**
	 * 微信完成台卡交易
	 * @param request
	 * @param phone 手机号
	 * @param sign
	 * @param deskcardCode 台卡编号
	 * @param deskcardId  台卡记录ID
	 * @param openId   
	 * @param tranAmt 订单总金额  
	 * @param actualTranAmt  订单实际付款金额
	 * @param nooffertranAmt 不参与优惠后计算金额
	 * @param couponCodes   优惠券id
	 * @param bonusAmount    积分数量
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tkWxPay",method = {RequestMethod.GET,RequestMethod.POST} )
	@ResponseBody
	public Response tkWxPay(HttpServletRequest request,HttpServletResponse response,Integer tranAmt,String phone,String sign,String deskcardCode,String deskcardId,String openId,
			Integer actualTranAmt,Integer nooffertranAmt,String couponCodes,Integer bonusAmount,Integer usePackage,String payPwd) throws Exception{
		logBefore(logger, "---------------------------------------------------微信完成台卡交易请求------------------------------------------");
		 PageData pd = new PageData();
		 pd = this.getPageData(); 
		System.out.println(pd); 
		String notifyUrl = HOME_URL + "/api/pay/wxpayNotify";
		String frontUrl = HOME_URL + "/api/pay/tkPayNotify";
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("支付金额", tranAmt+"");
        map.put("台卡编号", deskcardCode);
        map.put("台卡记录ID", deskcardId);
        map.put("openId不能为空", openId);
        map.put("签名", sign);
		String nullParam=Response.checkNull(map);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		if(tranAmt<=0){ 
			return Response.getError("请输入正确的消费金额");
		}
		if(usePackage!=null&&usePackage.intValue()==1&&Tools.isEmpty(payPwd)){
			return Response.getError("请输入支付密码");
		}
		if(Tools.notEmpty(couponCodes)&&actualTranAmt==null){ 
			return Response.getError("实付金额不能为空");
		}
		String signInfo = new SimpleHash("SHA-1", deskcardCode, deskcardId).toString();
		if (!signInfo.equals(sign)) {
			return Response.getError("参数非法");
		}
		
        try {
        	/**检查这个用户与这个门店的 是否未支付的订单**/
        	wxApiWalletServiceService.checkUserShopOrderStatus(phone,deskcardId,deskcardCode);
        	String mchCreateIp=Tools.getIpAddr(request);
        	if(usePackage!=null&&usePackage.intValue()==1){
        		Response  resultMap=wxApiWalletServiceService.updateWalletPay(
        				tranAmt, mchCreateIp, phone, notifyUrl, deskcardId, "台卡钱包支付", deskcardCode, payPwd,
                        actualTranAmt, nooffertranAmt,couponCodes,bonusAmount,ROOT_HOME_URL);
        		if(resultMap.isStatus() && resultMap.getCode()==0){

					logger.info("========="+resultMap);
					logger.info("========="+resultMap.isStatus());
					logger.info("========="+resultMap.getCode());
        			logger.info("========="+(TradeOffline)resultMap.getData_extend());
        			TradeOffline tradeOffline=(TradeOffline)resultMap.getData_extend();
        			profitStatisService.saveOneOrderProfitCalculate(tradeOffline) ;
        			memberService.insertMemberTradeDataAsyn(tradeOffline.getPayerId(),tradeOffline.getRealAmount(),tradeOffline.getBonusValue());
        		}
        		return resultMap;
        	}else{
				logBefore(logger, "==================updateTkWxPay=================");
        		Response  resultMap=wxApiWalletServiceService.updateTkWxPay(tranAmt, mchCreateIp, phone, notifyUrl, deskcardId, "微信台卡支付", deskcardCode, openId,
                      	 actualTranAmt, nooffertranAmt,couponCodes,bonusAmount,ROOT_HOME_URL,frontUrl);
        		return resultMap;
        		// h5payURL
        		
//        		return response.sendRedirect("");
        	}	
        	
		} catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	
	/**
	 * 重定向至支付宝授权页
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/tkAliPayIndex",method = {RequestMethod.GET,RequestMethod.POST} )
	public String tkAliPayIndex(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		 PageData pd = new PageData();
		 pd = this.getPageData();
		String shopId = pd.getString("shopId");
		 String deskcardCode=pd.getString("deskcardCode");//编号
		 String deskcardId=pd.getString("deskcardId");//商户号
		 String sign = new SimpleHash("SHA-1", deskcardCode, deskcardId).toString();
		 String merchantName=pd.getString("merchantName");
		 String name = java.net.URLEncoder.encode(merchantName,"utf-8");
		logger.info(">>>>>>>>>tkAliPayIndex 门店名称>>>>"+name);
		 // 支付宝云流页面  http://sbs-test.eboss007.com/pay/recharge/ali_pay_yunliu.html
		 PrePurchaseActivity prePurchaseActivity= wxApiWalletServiceService.findPrePurchaseActivity(deskcardCode, deskcardId);
		 String url=null;
		 if(prePurchaseActivity!=null){
			 url=String.format("%s/pay/recharge/ali_pay_yunliu.html?discount=%d&",ROOT_HOME_URL,prePurchaseActivity.getCustomerBenefitAmount());
		 }else{
			 
			//此处根据不同的支付类型跳转到不同的路径   迅联支付和新大陆支付 直接给支付地址           
			 DeviceDeskCard deviceDeskCard=deviceService.getDeviceDeskCardId(Long.valueOf(deskcardId));
			 
			 if(deviceDeskCard.getDeskcardOrganization()==(byte)BizEnum.DeskCardInNetCompany.fuqianla.getType()){
				 url=String.format("%s/pay/recharge/ali_pay.html?",ROOT_HOME_URL);
			 }else if(deviceDeskCard.getDeskcardOrganization()==(byte)BizEnum.DeskCardInNetCompany.xindalu.getType()){
				 url=String.format("%s/pay/recharge/ali_pay_jpy.html?",ROOT_HOME_URL);
			 }
			 
			 
		 }
		 
		  url=url+"deskcardCode="+deskcardCode+"&deskcardId="+deskcardId+"&sign="+sign+"&merchantName="+name+"&shopId="+shopId;
		logger.info(">>>>>>>url>>>>"+url);
		 response.sendRedirect(url);
		 return null; 
	}
	
	
	
	/**
	 * 支付宝台卡交易
	 * 
	 * @param groupId
	 * @return
	 */
	@RequestMapping(value = "tkAliPay")
	@ResponseBody
	public  Response tkAliPay(HttpServletRequest request,Integer tranAmt,String phone,String deskcardId,String deskcardCode,String sign,
			Integer actualTranAmt,Integer nooffertranAmt,String couponCodes,Integer bonusAmount,Integer usePackage,String payPwd) throws Exception{
		 logBefore(logger, "支付宝台卡交易");
		 logBefore(logger, "支付宝台卡交易总金额"+tranAmt);
		 logBefore(logger, "实付金额"+actualTranAmt);
		 logBefore(logger, "usePackage"+usePackage);
	   HashMap<String, String> map = new HashMap<String, String>();
	        map.put("支付金额", tranAmt+"");
	       
	        map.put("台卡编号", deskcardCode);
	        map.put("台卡记录ID", deskcardId);      
	        map.put("签名", sign);  
			String nullParam=Response.checkNull(map);  
			if (null != nullParam) {
				return Response.getError(nullParam+"不能为空");
			}
			if(Tools.notEmpty(couponCodes)&&actualTranAmt==null){ 
				return Response.getError("实付金额不能为空");
			}
			if(usePackage!=null&&usePackage.intValue()==1&&payPwd==null){
				return Response.getError("请输入支付密码");
			}
			if(tranAmt<=0){ 
				return Response.getError("请输入正确的消费金额");
			}
			String signInfo = new SimpleHash("SHA-1", deskcardCode, deskcardId).toString();
			if (!signInfo.equals(sign)) {
				return Response.getError("参数非法");
			}
		try {
			String notifyUrl = HOME_URL + "/api/pay/wxpayNotify";
			String mchCreateIp=Tools.getIpAddr(request);
			
			/**检查这个用户与这个门店的 是否未支付的订单**/
        	wxApiWalletServiceService.checkUserShopOrderStatus(phone,deskcardId,deskcardCode);
        	
			if(usePackage!=null&&usePackage.intValue()==1){
        		Response  resultMap=wxApiWalletServiceService.updateWalletPay(tranAmt, mchCreateIp, phone, notifyUrl, deskcardId, "台卡钱包支付", deskcardCode, payPwd,
                      	 actualTranAmt, nooffertranAmt,couponCodes,bonusAmount,ROOT_HOME_URL);
        		
        		if(resultMap.isStatus()&&resultMap.getCode()==0){
        			TradeOffline tradeOffline=(TradeOffline)resultMap.getData_extend();
        			profitStatisService.saveOneOrderProfitCalculate(tradeOffline) ;
        			memberService.insertMemberTradeDataAsyn(tradeOffline.getPayerId(),tradeOffline.getRealAmount(),tradeOffline.getBonusValue()); 
        		}  
        		return resultMap;
        	}else{
				logBefore(logger, "==================updateTkAliPay=================");
				Response resultMap=wxApiWalletServiceService.updateTkAliPay(tranAmt, mchCreateIp, phone, notifyUrl, deskcardId, "支付宝台卡充值", deskcardCode,
						 actualTranAmt, nooffertranAmt,couponCodes,bonusAmount,ROOT_HOME_URL);
				return resultMap;
        	}
		} catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	
	

	/**
	 * 台卡 交易结果回调  
	 * @param groupId
	 * @return
	 */
	@RequestMapping(value = "/wxpayNotify")
	@ResponseBody
	public  String wxpayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception{
		PageData pd = new PageData();
		 pd = this.getPageData();
		logBefore(logger, "回调参数"+pd);
		String outOrderNum=pd.getString("outOrderNum");

		if (outOrderNum.startsWith(Const.TK_DEVICE)||outOrderNum.startsWith(Const.XYJ_DEVICE)) {
			String orderNo=pd.getString("orderNo");
			String tradeStatus=pd.getString("tradeStatus"); 
			
					TradeOffline tradeOffline=wxApiWalletServiceService.updateTkOrderState(outOrderNum,orderNo,tradeStatus,ROOT_HOME_URL); 
					if(tradeOffline!=null){
						//只有transResult为1才表示支付成功发送通知,其他表示支付失败
			    		if(pd.getString("tradeStatus").equals("1")&&tradeOffline!=null){
							TradeOffline to = tradeService.selectByOrderId(outOrderNum);
							//if(to.getReceiverType() == 5) {//如果是商户商品，则进行推送
								//获取商户账号
								Userbase userbase = shopMapper.getUserNameByShopId(Long.parseLong(to.getReceiverId()));
								//发送支付成功推送信息
								Notice notice = new Notice();
								try {
									notice.setNoticetype(0);
									notice.setSender(to.getGroupId());
									notice.setReceiver(userbase.getUsername());
									notice.setNoticetitle("您有一笔新的收入");
									notice.setNoticetarget("ACCOUNT");
									notice.setNoticebody("台卡收入" + Double.parseDouble(to.getRealAmount()+"")/100 + "元");
									notice.setGroupid(to.getGroupId());
									notice.setNoticestatus(1);
									notice.setIsplay(1);
									notice.setType(4);
									notice.setTvalue(to.getId() + "#" + (to.getPayerId()!= null?to.getPayerId():0));
									appNoticeService.sendNoticeToUsers(notice);
								} catch (Exception e) {
									e.printStackTrace();
								}
							//}
							/*//结算积分给门店 start
							Long shopid = Long.parseLong(to.getReceiverId());
							Integer bonusamount = to.getBonusAmount();
							if(bonusamount != 0) {
								float settlerate = 0;
								//根据shopid获取积分结算规则
								BonusVerifyRule bonusVerifyRule = bonusVerifyRuleMapper.qyeryShopVerifyRule(shopid);
								if (bonusVerifyRule != null) {//如果有门店自定义的
									settlerate = bonusVerifyRule.getSettleRate();
								} else {//如果商圈给门店设置的
									bonusVerifyRule = bonusVerifyRuleMapper.selectBonusSettleRate(shopid, userbase.getGroupId());
									if (bonusVerifyRule != null) {
										settlerate = bonusVerifyRule.getSettleRate();
									} else {
										bonusVerifyRule = bonusVerifyRuleMapper.selectBonusVeriftyRuleByGroupId(userbase.getGroupId());
										if (bonusVerifyRule != null) {
											settlerate = bonusVerifyRule.getSettleRate();
										}
									}
								}

								//计算积分
								if (settlerate != 0) {
									int bonus = (int) (bonusamount * settlerate / 100);
									//积分结算给门店
									bonusVerifyShopMapper.insertShopVerifyBonus(userbase.getGroupId(), shopid, bonus);

									//添加积分结算记录
									BonusVerifyLog record1 = new BonusVerifyLog();
									record1.setGmtCreate(new Date());
									record1.setGmtModified(new Date());
									record1.setGroupId(userbase.getGroupId());
									record1.setMemberId(tradeOffline.getPayerId());
									record1.setVerifyType(ActivityEnum.BonusVerityType.Consume.getType());
									record1.setAdjustAmount(bonus);
									record1.setShopId(shopid);
									record1.setOrderId(tradeOffline.getId());
									record1.setAdjustStatus(ActivityEnum.BonusVerityStatus.OutAccounted.getType());
									bonusVerifyLogMapper.insert(record1);
								}
							}
							//结算积分给门店 end*/
							logger.info( "回调成功");
			    		}else{
			    			logger.info( "回调修改失败");
			    		}
					}else{
						logBefore(logger, "回调修改失败");
						
					}
					return "SUCCESS";
			
		}else if(outOrderNum.startsWith(Const.XLTK_DEVICE)){
//			{tradeTime=2018-02-07 11:03:01, businessCode=fea2fe9fab3842a8410d333088f320f1, 
//			orderNo=22018020711034981, SignMsg=6EE3D53046CA6681A6C18DFFA2DB8157,
//			goodDedc=test, openid=o2eT9wPZRiL6a0bvX5SZdF36OnhU,
//			tradeStatus=1, remark=, order_type=WECHAT, outOrderNum=XLTK20180207110205836672, desc=您在商户（迅联测试商户)消费0.02元}
			String orderNo=pd.getString("orderNo");
			String tradeStatus=pd.getString("tradeStatus");
					TradeOffline tradeOffline=wxApiWalletServiceService.updateTkOrderState(outOrderNum,orderNo,tradeStatus,ROOT_HOME_URL); 
			
					if(tradeOffline!=null){
						//只有transResult为1才表示支付成功发送通知,其他表示支付失败
			    		if(pd.getString("tradeStatus").equals("1")&&tradeOffline!=null){
			    			logger.info( "回调成功");
			    		}else{
			    			logger.info( "回调修改失败");
			    		}
					}else{
						logBefore(logger, "回调修改失败");
						
					}

			return "SUCCESS";
		}else{
			return "-1"; 
		}
		
	}
			
	
	/**
	 * 台卡(预采购) 交易结果回调  
	 * @param groupId
	 * @return
	 */
	@RequestMapping(value = "/ycgWxpayNotify")
	@ResponseBody
	public  String ycgWxpayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception{
		logBefore(logger, "----------------------------------------------预采购 微信公众号 交易结果回调-------------------------------------------------");
		//{tradeTime=2017-08-07 15:30:05, businessCode=102900160914003, orderNo=201708071530048668673, SignMsg=67C6C3470D2E43173D36128E0CEEA179, goodDedc=掌富测试（勿删）台卡收银, openid=o_UGbs5-8Ad0YCeu08NfqtFOHDOs,
		//tradeStatus=1, remark=, order_type=WECHAT, outOrderNum=20170807153004RTQRREUR, url=http://weixin1.eboss007.com/pay/100020091219001/index.html?rid=15240, desc=您在商户（上海掌富网络技术有限公司)消费0.01元}
		 PageData pd = new PageData();
		 pd = this.getPageData();
		logBefore(logger, "交易订单号"+pd.getString("orderNo"));
		String outOrderNum=pd.getString("outOrderNum");
		String orderNo=pd.getString("orderNo");
		String tradeStatus=pd.getString("tradeStatus");
		TradeOffline tradeOffline=wxApiWalletServiceService.updateYcgOrderState(outOrderNum,orderNo,tradeStatus,ROOT_HOME_URL); 
		Boolean flag=false;
		try {
			flag=true;
			profitStatisService.saveOneOrderProfitCalculate(tradeOffline.getId());
		} catch (Exception e) {
			e.printStackTrace();
			 logger.info("----单笔交易分润计算异常");
		}
		if(tradeOffline!=null){
			//只有transResult为1才表示支付成功发送通知,其他表示支付失败
    		if(pd.getString("tradeStatus").equals("1")&&tradeOffline!=null){
    			logger.info( "回调修改成功");  
    		}else{
    			logger.info( "回调修改失败");
    		}
		}else{
			logBefore(logger, "回调修改失败");
			
		}
		if(flag){
			return "SUCCESS";
		}else{
			return null;
		}
		
	}
	
	
	/**
	 * 会员提现卡绑定 
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/memberBankCard", method = {RequestMethod.GET,RequestMethod.POST})
	@ResponseBody 
	public Response memberBankCard(String memberId, String accName,String accNo,String bankName,String certNo, String mobile, 
								    String payPwd,String cardType,String bankCode) throws Exception {
		logBefore(logger, "银行卡快捷支付认证");
		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("会员编号", memberId);
		resultMap.put("持卡人姓名 ", accName);
		resultMap.put("银行卡号", accNo);
		resultMap.put("银行名", bankName);
		resultMap.put("身份证号", certNo);
		resultMap.put("手机号", mobile);
		resultMap.put("银行卡类型", cardType);
		resultMap.put("支付密码", payPwd);
		resultMap.put("联行号", bankCode);
		String nullParam=Response.checkNull(resultMap);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		if(!Tools.checkMobileNumber(mobile)){
			return Response.getError("手机号码格式不对");
		}
		if (!Pattern.matches("^[\u4E00-\u9FFF]+$", accName)) {
			return Response.getError("持卡姓名必须为中文");
		}
		//如果内容一致 且提交时间小于1分钟 判断为重复提交
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		String repeatAccNo=(String) session.getAttribute(accNo);
//		Boolean flag=tokenService.checkToken(memberId,token);
//		if(!flag){ 
//			return Response.getError("token错误");
//		}
		try {
			if(Tools.isEmpty(repeatAccNo)){	
				wxApiMemberService.updateMemberBankCard(memberId, accName, accNo, bankName, certNo, mobile, payPwd, cardType,bankCode);
				session.setTimeout(3*1000);
				return Response.getSuccess(null);
			}else{
				return Response.getError("操作太快,休息一会再试");
			}
		} catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
		
	}
	
	
	/**
	 * 银行卡快捷支付充值认证
	 * @param request
	 * @param memberId
	 * @param tranAmt
	 * @param bankCode
	 * @param cardNum
	 * @param idName
	 * @param idNo
	 * @param cardMobile
	 * @param cardCvn
	 * @param cardExpdate
	 * @param payType 1无充值送  2比例送 3 固定送
	 * @param orgOrderNum
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/bankcardverify", method = {RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Response bankcardverify(HttpServletRequest request,String memberId, String tranAmt,String bankCode,String cardNum, String idName, String idNo,
								   String cardMobile,  String cardCvn, String cardExpdate,String payType) throws Exception {
		logBefore(logger, "银行卡快捷支付认证");

		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("会员编号", memberId);
		resultMap.put("交易金额", tranAmt);
		resultMap.put("银行行号 ", bankCode);
		resultMap.put("银行卡号", cardNum);
		resultMap.put("持卡人姓名", idName);
		resultMap.put("身份证号码", idNo);
		resultMap.put("银行预留手机号", cardMobile);
		resultMap.put("消费类型", payType);
		String nullParam=Response.checkNull(resultMap);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		if(!Tools.checkMobileNumber(cardMobile)){
			return Response.getError("手机号码格式不对");
		}
//		Boolean flag=tokenService.checkToken(memberId,token);
//		if(!flag){ 
//			return Response.getError("token错误");
//		}
		try {
			wxApiMemberService.insertBankCardVefity(memberId,tranAmt,bankCode,cardNum,
					idName,idNo,cardMobile,cardCvn,cardExpdate,Tools.getIpAddr(request),payType);
			return Response.getSuccess(null);
		} catch (ApplicationException ae) {
			logger.error(ae);
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			return Response.getError("服务器异常");
		}
	}
	
	
	/**
	 * 银行卡快捷支付（消费）认证
	 * @param request
	 * @param memberId
	 * @param tranAmt
	 * @param bankCode
	 * @param cardNum
	 * @param idName
	 * @param idNo
	 * @param cardMobile
	 * @param cardCvn
	 * @param cardExpdate
	 * @param orgOrderNum
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/bankcardverifyConsumption", method = {RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Response bankcardverifyConsumption(HttpServletRequest request,String memberId, String tranAmt,String bankCode,String cardNum, String idName, String idNo,
								   String cardMobile,  String cardCvn, String cardExpdate,String orgOrderNum) throws Exception {
		logBefore(logger, "银行卡快捷支付认证");

		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("会员编号", memberId);
		resultMap.put("交易金额", tranAmt);
		resultMap.put("银行行号 ", bankCode);
		resultMap.put("银行卡号", cardNum);
		resultMap.put("持卡人姓名", idName);
		resultMap.put("身份证号码", idNo);
		resultMap.put("银行预留手机号", cardMobile);
		String nullParam=Response.checkNull(resultMap);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		if(!Tools.checkMobileNumber(cardMobile)){
			return Response.getError("手机号码格式不对");
		}
		try {
			wxApiMemberService.insertBankCardVefityConsumption(memberId,tranAmt,bankCode,cardNum,
					idName,idNo,cardMobile,cardCvn,cardExpdate,Tools.getIpAddr(request),orgOrderNum);
			return Response.getSuccess(null);
		}catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	
	
	
	/**
	 * 第一次绑卡快捷支付充值(消费)认证
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/bankcardverifysubmit", method = {RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Response bankcardverifysubmit(HttpServletRequest request,String memberId, String code) throws Exception {
		logBefore(logger, "银行卡快捷支付认证");
		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("会员编号", memberId);
		resultMap.put("验证码", code);
		String nullParam=Response.checkNull(resultMap);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
//		Boolean flag=tokenService.checkToken(memberId,token);
//		if(!flag){ 
//			return Response.getError("token错误");
//		}
		try {
			wxApiMemberService.updatebankcardverifysubmit(memberId,code,Tools.getIpAddr(request));
			return Response.getSuccess(null);
		}catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	
	/**
	 * 已存在银行卡快捷支付充值认证
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/existCardsubmit", method = {RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Response existCardsubmit(HttpServletRequest request,String memberId,String cardId,String tranAmt,String payType,String orgOrderNum) throws Exception {
		logBefore(logger, "银行卡快捷支付认证");
		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("会员编号", memberId);
		resultMap.put("银行卡编号", cardId);
		resultMap.put("交易金额", tranAmt);
		resultMap.put("交易类型", payType);
		String nullParam=Response.checkNull(resultMap);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		try {
			wxApiMemberService.updateExistCardsubmit(memberId,Tools.getIpAddr(request),cardId,tranAmt,payType,orgOrderNum);
			//支付成功 进行微信模板消息推送---
			return Response.getSuccess(null);
		} catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	
	/**
	 * 已存在银行卡快捷支付消费认证
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/existCardsubmitConsumption", method = {RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Response existCardsubmitConsumption(HttpServletRequest request,String memberId,String cardId,String tranAmt,String payType,String orgOrderNum) throws Exception {
		logBefore(logger, "银行卡快捷支付认证");
		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("会员编号", memberId);
		resultMap.put("银行卡编号", cardId);
		resultMap.put("交易金额", tranAmt);
		String nullParam=Response.checkNull(resultMap);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		try {
			wxApiMemberService.updateExistCardsubmitConsumption(memberId,Tools.getIpAddr(request),cardId,tranAmt,orgOrderNum);
			return Response.getSuccess(null);
		} catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	
	/**
	 * 查询会员银行卡列表 
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/bankcardlist", method = {RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Response bankList(String memberId) throws Exception {
		logBefore(logger, "查询会员银行列表");
		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("会员编号", memberId);
		String nullParam=Response.checkNull(resultMap);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		try { 
			Response response = wxApiMemberService.bankList(memberId);
			return response;
		} catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}

	/**
	 * 查询会员银行卡详情
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/bankcarddetail", method = {RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Response bankCardDetil( String memberId, String cardId) throws Exception {
		logBefore(logger, "查询会员银行卡详情");
		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("会员编号", memberId);
		resultMap.put("银行卡编号", cardId);
		String nullParam=Response.checkNull(resultMap);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
//		Boolean flag=tokenService.checkToken(memberId,token);
//		if(!flag){ 
//			return Response.getError("token错误");
//		}
		try {
			Map<String, Object> map = wxApiMemberService.bankCardDetil(memberId,cardId);
			if(map == null || map.size()==0){
				return Response.getError("未查询到记录");
			}
			return Response.getSuccess(map);
		} catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}

	/**
	 * 删除绑定银行卡信息
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/delbindcard", method = {RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Response delBindCard(String memberId,String cardId) throws Exception {
		logBefore(logger, "删除绑定银行卡信息");
		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("会员编号", memberId);
		resultMap.put("银行卡编号", cardId);
		String nullParam=Response.checkNull(resultMap);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		try {
			wxApiMemberService.updateUnBindBankCard(memberId,cardId);
			return Response.getSuccess(null);
		}catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	
	
	/**
	 * 用户申请提现-信用卡还款   
	 *
	 * @return 
	 * @throws Exception
	 */
	@RequestMapping(value = "/wxWithdrawal",  method = {RequestMethod.GET,RequestMethod.POST} )
	@ResponseBody
	public Response wxWithdrawal(HttpServletRequest request,String memberId,Integer tranAmt,String cardId,
			String payPwd,String token,Integer fee) throws Exception {
		logBefore(logger, "用户申请提现-信用卡还款");
		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("会员编号", memberId);
		resultMap.put("银行卡编号", cardId);
		resultMap.put("提现金额", tranAmt+"");
		resultMap.put("支付密码", payPwd);
		resultMap.put("手续费", fee+"");
		String nullParam=Response.checkNull(resultMap);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		if (tranAmt<=200) {
			return Response.getError("提现金额不低于2元");
		}
		if (fee<0) {
			return Response.getError("手续费不能小于0");
		}
		logBefore(logger, "用户手续费--------------------------------------------------------"+fee);
		try { 
			//因提现回调通知可能早于返回结果通过 所有处理结果2步操作
			HashMap<String, Object> hashmap = wxApiMemberService.updateWxlyWithdraw(memberId, tranAmt, cardId, payPwd,fee);
			if(hashmap!=null){
				Response map = wxApiMemberService.sendWxlyWithdraw(hashmap, tranAmt, payPwd,fee);
				logBefore(logger, "用户申请提现-信用卡还款申请成功--------------------------------------------------------");
				return map;
			}else{
				return Response.getError("服务器异常");
			}
		}catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	
	

	
	
	/**
	 * 微信完成台卡交易 (预采购)
	 * @param request
	 * @param phone 手机号
	 * @param sign
	 *  map.put("台卡编号", deskcardCode);
       map.put("台卡记录ID", deskcardId);  
	 * @param openId   
	 * @param tranAmt 订单总金额  
	 * @param actualTranAmt  订单实际付款金额
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tkYcgWxPay",method = {RequestMethod.GET,RequestMethod.POST} )
	@ResponseBody
	public Response tkYcgWxPay(HttpServletRequest request,Integer tranAmt,String phone,String sign,String deskcardCode,String deskcardId,String openId,
			Integer actualTranAmt,Integer usePackage,String payPwd) throws Exception{
		logBefore(logger, "---------------------------------------------------微信预采购完成台卡交易请求------------------------------------------");
		PageData pd = new PageData();
		pd = this.getPageData();
		System.out.println(pd); 
		String notifyUrl = HOME_URL + "/api/pay/ycgWxpayNotify";
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("支付金额", tranAmt+"");
        map.put("台卡编号", deskcardCode);
        map.put("台卡记录ID", deskcardId);  
        map.put("openId不能为空", openId);
        map.put("签名", sign);
		String nullParam=Response.checkNull(map);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		if(usePackage!=null&&usePackage.intValue()==1&&payPwd==null){
			return Response.getError("请输入支付密码");
		}
		if(tranAmt<=0){ 
			return Response.getError("请输入正确的消费金额");
		}
		String signInfo = new SimpleHash("SHA-1", deskcardCode, deskcardId).toString();
		if (!signInfo.equals(sign)) {
			return Response.getError("参数非法");
		}
		System.out.println("tkWxPay..."+JSONObject.toJSONString(map));
        try {
        	/**检查这个用户与这个门店的 是否未支付的订单**/
        	wxApiWalletServiceService.checkUserShopOrderStatus(phone,deskcardId,deskcardCode);
        	
        	String mchCreateIp=Tools.getIpAddr(request);
        	if(usePackage!=null&&usePackage.intValue()==1){
        		Response  resultMap=wxApiWalletServiceService.updateWalletYcgPay(tranAmt, mchCreateIp, phone, notifyUrl, deskcardId, "台卡钱包支付", deskcardCode, payPwd,
                      	 actualTranAmt);
                      return resultMap;
        	}else{
        	   Response  resultMap=wxApiWalletServiceService.updateTkYcgWxPay(tranAmt, mchCreateIp, phone, notifyUrl, deskcardId, "微信台卡预采购支付", deskcardCode, openId,
            	 actualTranAmt);
        	   return resultMap;
        	}
          
		}catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	
	
	/**
	 * 支付宝台卡交易 (预采购)
	 * 
	 * @param groupId
	 * @return
	 */
	@RequestMapping(value = "tkYcgAliPay")
	@ResponseBody
	public  Response tkYcgAliPay(HttpServletRequest request,Integer tranAmt,String phone,String deskcardId,String deskcardCode,String sign,
			Integer actualTranAmt,Integer usePackage,String payPwd) throws Exception{
		 logBefore(logger, "支付宝台卡预采购交易");
		 logBefore(logger, "支付宝台卡预采购交易总金额"+tranAmt);
	   HashMap<String, String> map = new HashMap<String, String>();
	   map.put("支付金额", tranAmt+"");
       map.put("台卡编号", deskcardCode);
       map.put("台卡记录ID", deskcardId);  
	        map.put("签名", sign);  
			String nullParam=Response.checkNull(map);  
			if (null != nullParam) {
				return Response.getError(nullParam+"不能为空");
			}
			if(tranAmt<=0){ 
				return Response.getError("请输入正确的消费金额");
			}
			if(usePackage!=null&&usePackage.intValue()==1&&payPwd==null){
				return Response.getError("请输入支付密码");
			}
			String signInfo = new SimpleHash("SHA-1", deskcardCode, deskcardId).toString();
			if (!signInfo.equals(sign)) {
				return Response.getError("参数非法");
			}
			System.out.println("tkWxPay..."+JSONObject.toJSONString(map));
		try {
			/**检查这个用户与这个门店的 是否未支付的订单**/
        	wxApiWalletServiceService.checkUserShopOrderStatus(phone,deskcardId,deskcardCode);
			String notifyUrl = HOME_URL + "/api/pay/ycgWxpayNotify";
			String mchCreateIp=Tools.getIpAddr(request);
			if(usePackage!=null&&usePackage.intValue()==1){
        		Response resultMap=wxApiWalletServiceService.updateWalletYcgPay(tranAmt, mchCreateIp, phone, notifyUrl, deskcardId,
        				"台卡钱包支付", deskcardCode, payPwd,actualTranAmt);
                      return resultMap;
        	}else{
			    Response resultMap=wxApiWalletServiceService.updateTkYcgAliPay(tranAmt, mchCreateIp, phone, notifyUrl, deskcardId, 
					  "支付宝预采购台卡消费",deskcardCode, actualTranAmt);
			  return resultMap;
        	}
		} catch (ApplicationException ae) {
			ae.printStackTrace();
			logger.error(ae);
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	
	
	/**
	 *  obd 授权首页
	 * @param orderId      订单编号
	 * @param realAmount   金额
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/obdIndex", method = {RequestMethod.GET,RequestMethod.POST} )
	public String obdIndex(String orderId,String realAmount,
			HttpServletRequest request, HttpServletResponse response, Model model) throws Exception{
		logBefore(logger, "obd台卡授权首页"+HOME_URL);
		logBefore(logger, "obd台卡授权首页"+ROOT_HOME_URL);
		TradeOffline tradeOffline=wxApiWalletServiceService.findOrderId(orderId, BizEnum.TransactionStatus.WaitingForPay.getType());
		if(tradeOffline==null){
			model.addAttribute("msg", "未查询到未支付的订单");
			return "payError";
		}
		String type = request.getHeader("user-agent");
		if (type.toLowerCase().indexOf("micromessenger") >= 0) {
			Long groupId=tradeOffline.getGroupId();
			//判断当前台卡对应的 门店是否 处于预采购状态
			String  url=HOME_URL+"/api/pay/obdWxPayIndex"; 		
			 wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(groupId));				
			 String href = wxService.oauth2buildAuthorizationUrl(
					 url+"?orderId="+orderId+"&realAmount="+realAmount+"&groupId="+groupId, WxConsts.OAUTH2_SCOPE_BASE, "");  
			 logBefore(logger, "------------------------------------获取微信openId第1步结束-----------------------------------"+href);
			 response.sendRedirect(href);
			 return null;
		}else 
		if (type.toLowerCase().indexOf("alipayclient") >= 0) {
			// 支付宝
			String url=HOME_URL+"/api/pay/obdAliPayIndex"; ;
			String path = url+"?orderId="+orderId+"&realAmount="+realAmount;
			logBefore(logger, "支付宝授权url"+path);
			try {
				response.sendRedirect(path);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		// 请用微信或者支付宝扫描
		logBefore(logger, "----------------非微信或支付宝扫描---------------------");
		model.addAttribute("msg", "请用微信或者支付宝扫描");
		return "payError";
	}
	
	
	
	/**
	 * obd重定向至微信页
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/obdWxPayIndex",method = {RequestMethod.GET,RequestMethod.POST} )
	public String obdWxPayIndex(HttpServletRequest request, HttpServletResponse response) throws Exception{
		 logBefore(logger, "obd微信第二步授权开始");
		 PageData pd = new PageData();
		 pd = this.getPageData();
		 String groupId=pd.getString("groupId");
		 String code=pd.getString("code"); 
		 String orderId=pd.getString("orderId");
		 String realAmount=pd.getString("realAmount");
		 wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(Long.parseLong(groupId)));
		 WxMpOAuth2AccessToken wxMpOAuth2AccessToken = this.wxService.oauth2getAccessToken(code);  
		 String openId=wxMpOAuth2AccessToken.getOpenId();
		 String description="obd预采购";
		 String descriptionName = java.net.URLEncoder.encode(description,"utf-8");
		 String sign = new SimpleHash("SHA-1", orderId, realAmount).toString();
		 String url=String.format("%s/pay/recharge/obd_wx_pay.html?",ROOT_HOME_URL);
		 url=url+"openId="+openId+"&orderId="+orderId+"&realAmount="+realAmount+"&sign="+sign+"&description="+descriptionName;
		 logBefore(logger, "微信第二步授权结束");
		 response.sendRedirect(url);
		 return null; 
	}
	
	/**
	 * 重定向至支付宝授权页
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/obdAliPayIndex",method = {RequestMethod.GET,RequestMethod.POST} )
	public String obdAliPayIndex(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		 PageData pd = new PageData();
		 pd = this.getPageData();
		 String orderId=pd.getString("orderId");
		 String realAmount=pd.getString("realAmount");
		 String sign = new SimpleHash("SHA-1", orderId, realAmount).toString();
		 String url=String.format("%s/pay/recharge/obd_ali_pay.html?",ROOT_HOME_URL);
		 String description="obd预采购";
		 String descriptionName = java.net.URLEncoder.encode(description,"utf-8");
		 url=url+"orderId="+orderId+"&realAmount="+realAmount+"&sign="+sign+"&description="+descriptionName;;
		 response.sendRedirect(url);
		 return null; 
	}
	
	
	/**
	 * 微信完成台卡交易
	 * @param request
	 * @param phone 手机号
	 * @param sign
	 * @param deskcardCode 台卡编号
	 * @param deskcardId  台卡记录ID
	 * @param openId   
	 * @param tranAmt 订单总金额  
	 * @param actualTranAmt  订单实际付款金额
	 * @param nooffertranAmt 不参与优惠后计算金额
	 * @param couponUserId   优惠券id
	 * @param bonusAmount    积分数量
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/obdWxPay",method = {RequestMethod.GET,RequestMethod.POST} )
	@ResponseBody
	public Response obdWxPay(HttpServletRequest request,String orderId,Integer realAmount,String openId,String sign) throws Exception{
		logBefore(logger, "---------------------------------------------------微信完成台卡交易请求------------------------------------------");
		 PageData pd = new PageData();
		 pd = this.getPageData();
		System.out.println(pd); 
		String notifyUrl = HOME_URL + "/api/pay/obdWxpayNotify";
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("订单编号", orderId);
        map.put("支付金额", realAmount+"");
        map.put("openId不能为空", openId);
        map.put("签名", sign);
		String nullParam=Response.checkNull(map);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		if(realAmount<=0){ 
			return Response.getError("消费金额必须大于0");
		}
		String signInfo = new SimpleHash("SHA-1", orderId, realAmount+"").toString();
		if (!signInfo.equals(sign)) {
			return Response.getError("参数非法");
		}
		
        try {
        	String mchCreateIp=Tools.getIpAddr(request);
        	Response  resultMap=wxApiWalletServiceService.updateObdWxPay(orderId, realAmount, "微信obd台卡支付", openId, mchCreateIp,notifyUrl);
            return resultMap;
		} catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	
	
	/**
	 * 支付宝台卡交易
	 * 
	 * @param groupId
	 * @return
	 */
	@RequestMapping(value = "obdAliPay")
	@ResponseBody
	public  Response obdAliPay(HttpServletRequest request,String orderId,Integer realAmount,String sign) throws Exception{
		 logBefore(logger, "支付宝台卡交易");
		 logBefore(logger, "支付宝台卡交易总金额"+realAmount);
	   HashMap<String, String> map = new HashMap<String, String>();
		    map.put("订单编号", orderId);
		    map.put("支付金额", realAmount+"");
	        map.put("签名", sign);  
			String nullParam=Response.checkNull(map);  
			if (null != nullParam) {
				return Response.getError(nullParam+"不能为空");
			}
			if(realAmount<=0){ 
				return Response.getError("请输入正确的消费金额");
			}
			String signInfo = new SimpleHash("SHA-1", orderId, realAmount+"").toString();
			if (!signInfo.equals(sign)) {
				return Response.getError("参数非法");
			   }
		try {
			String notifyUrl = HOME_URL + "/api/pay/obdWxpayNotify";
			String mchCreateIp=Tools.getIpAddr(request);
			Response resultMap=wxApiWalletServiceService.updateObdAliPay(orderId, realAmount, "支付宝obd台卡充值", mchCreateIp, notifyUrl);
			return resultMap;
		}catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	
	/**
	 * 台卡 obd交易结果回调  
	 * @param groupId
	 * @return
	 */
	@RequestMapping(value = "/obdWxpayNotify")
	@ResponseBody
	public  String obdWxpayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception{
		logBefore(logger, "----------------------------------------------obd 微信公众号 交易结果回调-------------------------------------------------");
		//{tradeTime=2017-08-07 15:30:05, businessCode=102900160914003, orderNo=201708071530048668673, SignMsg=67C6C3470D2E43173D36128E0CEEA179, goodDedc=掌富测试（勿删）台卡收银, openid=o_UGbs5-8Ad0YCeu08NfqtFOHDOs,
		//tradeStatus=1, remark=, order_type=WECHAT, outOrderNum=20170807153004RTQRREUR, url=http://weixin1.eboss007.com/pay/100020091219001/index.html?rid=15240, desc=您在商户（上海掌富网络技术有限公司)消费0.01元}
		 PageData pd = new PageData();
		 pd = this.getPageData();
		logBefore(logger, "交易订单号"+pd.getString("orderNo"));
		TradeOffline tradeOffline=wxApiWalletServiceService.updateObdOrderState(pd.getString("orderNo"),pd.getString("tradeStatus")); 
		if(tradeOffline!=null){
			logBefore(logger, "回调修改成功");
			return "SUCCESS";
		}else{
			logBefore(logger, "回调修改失败");
			return null;
		}
		
		
	}
	
	
	
	
	
	/**
	 * 授权首页     http://sbs.eboss007.com/EBosService/?chcd=WXP&errorDetail=%E5%8F%96%E6%B6%88&goodsInfo=test&mchntid=S001737&orderNum=22018020618123178&state=-1&transCurrency=HKD&txamt=000000000002
	 * @param deskcardCode  台卡编号
	 * @param deskcardId    主键ID
	 * @param request   
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tkPayNotify", method = {RequestMethod.GET,RequestMethod.POST} )
	public String tkPayNotify(String chcd,String errorDetail,String goodsInfo,String mchntid,String orderNum,
			String state,String transCurrency,String txamt,
			HttpServletRequest request, HttpServletResponse response, Model model) throws Exception{
		
		logBefore(logger, "交易结果页");
		
		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("支付方式", chcd);
		resultMap.put("描述", errorDetail);
		resultMap.put("商品详情", goodsInfo);
		resultMap.put("机构号", mchntid);
		resultMap.put("订单号", orderNum);
		resultMap.put("交易状态", state);
		resultMap.put("币种", transCurrency);
		resultMap.put("终端", txamt);
		String nullParam = Response.checkNull(resultMap);
		if (null != nullParam) {
			model.addAttribute("msg", "非法请求");
			return "XLTkPay";
		}
		String description=null;
		switch (state) {
		case "1":
			description="支付成功";
			break;
		case "0":
			description="支付成功";
			break;	
		case "-1":
			description="支付取消";
			break;
		default:
			description="支付失败";
			break;
		}
		String payTypeName=chcd.equals("WXP")?"微信":"支付宝";
		model.addAttribute("msg", payTypeName+description);
		return "XLTkPay";
	}
	
	
	/**
	 * 用户被扫回调
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/bepayNotify")
	@ResponseBody
	public  String bepayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception{
		logBefore(logger, "----------------------------------------------用户被扫回调-------------------------------------------------");
		
//		{tradeTime=2018-02-11 16:59:35, businessCode=fea2fe9fab3842a8410d333088f320f1,
//		orderNo=22018021116599711, SignMsg=01E4C2BE536086250B1A07C83B53010D, goodDedc=test, openid=, tradeStatus=4, remark=, order_type=WECHAT, outOrderNum=XLTK20180211165903456536, 
//		desc=您在商户（迅联测试商户)消费0.03元}
//		2018-02-11 17:01:32 -32050 [http-nio-9091-exec-1] DEBUG   - Written [0000] as "application/json;charset=UTF-8"
//		using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@79b86be8]
		
//		businessCode.............fea2fe9fab3842a8410d333088f320f1
//		desc.............您在商户（迅联测试商户)消费0.02元
//		goodDedc.............test
//		openid.............
//		orderNo.............22018021117178931
//		order_type.............WECHAT
//		outOrderNum.............XLTK20180211171702334345
//		remark.............
//		tradeStatus.............4
//		tradeTime.............2018-02-11 17:17:24
//		SignMsg.............2D2EC6EF93177941D7D42C5481E25D4E
		PageData pd = new PageData();
		 pd = this.getPageData();
		logBefore(logger, "回调参数"+pd);
		return "0000";
	}
	
	
	
	
	/**
	 * 富友面对面收款用户被扫
	 * 
	 * @param groupId
	 * @return
	 */
	@RequestMapping(value = "fyScanCodePay")
	@ResponseBody
	public  Response fyScanCodePay(HttpServletRequest request) throws Exception{
		 logBefore(logger, "富友面对面收款用户被扫");

		 String authCode = getRequest().getParameter("authCode");
		 Integer tranAmt = Integer.parseInt(getRequest().getParameter("tranAmt"));
		 String groupId = getRequest().getParameter("groupId");
	   HashMap<String, String> map = new HashMap<String, String>();
		    map.put("收款码", authCode);
		    map.put("支付金额", tranAmt+"");
	        map.put("商户编号", groupId);
			String nullParam=Response.checkNull(map);  
			if (null != nullParam) {
				return Response.getError(nullParam+"不能为空");
			}
			if(tranAmt<=0){ 
				return Response.getError("请输入正确的消费金额");
			}
			
		try {
			String notifyUrl = HOME_URL + "/api/pay/fyScanCodePayNotify";
			String mchCreateIp=Tools.getIpAddr(request);
			Response resultMap=wxApiWalletServiceService.updatefyScanCodePay(authCode, tranAmt, groupId, mchCreateIp, notifyUrl);
			
			
			return resultMap;
		}catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
	
	
	/**
	 * 扫码收款交易结果查询
	 * @param groupId
	 * @return
	 */
	@RequestMapping(value = "fyScanCodeQuery")
	@ResponseBody
	public  Response fyScanCodeQuery(HttpServletRequest request) throws Exception{
		 logBefore(logger, "扫码收款交易结果查询  ");
		 String orderId = request.getParameter("orderId");
	   HashMap<String, String> map = new HashMap<String, String>();
		    map.put("订单编号", orderId);
			String nullParam=Response.checkNull(map);  
			if (null != nullParam) {
				return Response.getError(nullParam+"不能为空");
			}
		try {
			Response resultMap=wxApiWalletServiceService.updatefyScanCodeQuery(orderId);
			return resultMap;
		}catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}

	/**
	 * 洗衣机扫码支付  授权首页
	 * @param deskcardCode  台卡编号
	 * @param deskcardId    主键ID
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/xyjIndex", method = {RequestMethod.GET,RequestMethod.POST} )
	public String xyjIndex(String shortId,String curBal,String washtype, String memberId, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception{

		//获取洗衣机码对应的groupid    curBal
		MachineWasher machineWasher = machineWasherService.selectMachineByBoardId(shortId);
		
		

		if(machineWasher != null) {//如果设备存在
			if(machineWasher.getStatus() == 0) {//可使用
				Long groupId = machineWasher.getGroupId();
				//获取微信配置信息
				WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage=null;
				try {
					wxMpInMemoryConfigStorage = wxBaseService.getTokenByGroupId(groupId);
				} catch (Exception e1) {
					e1.printStackTrace();
					return "payError";   
				}
				String  url = HOME_URL+"/api/pay/xyjWxPayIndex";
				wxService.setWxMpConfigStorage(wxMpInMemoryConfigStorage);
				String href = wxService.oauth2buildAuthorizationUrl(
						url+"?boardid="+machineWasher.getBoardid()+"&shortId="+shortId+"&washtype="+washtype+"&groupId="+groupId+"&memberId="+memberId+"&curBal="+curBal,
						WxConsts.OAUTH2_SCOPE_BASE, "");
				logBefore(logger, "------------------------------------获取微信openId第1步结束-----------------------------------");
				response.sendRedirect(href);
				return null;
			} else if(machineWasher.getStatus() == 1) {//已使用状态,跳转到正在使用页面
				response.sendRedirect(ROOT_HOME_URL+"/xyj/using.html");
				return null;
			} else if(machineWasher.getStatus() == 4) {
				response.sendRedirect(ROOT_HOME_URL+"/xyj/starting.html");
				return null;
			} else {//故障状态,跳转到故障页面
				response.sendRedirect(ROOT_HOME_URL+"/xyj/error.html");
				return null;
			}
		}
		// 请用微信扫描
		logBefore(logger, "----------------非微信扫描---------------------");
		model.addAttribute("msg", "请用微信扫描");
		return "payError";
	}



	/**
	 * 重定向至微信页
	 * @param request
	 * @param response
	 * @param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/xyjWxPayIndex",method = {RequestMethod.GET,RequestMethod.POST} )
	public String xyjWxPayIndex(HttpServletRequest request, HttpServletResponse response) throws Exception{
		logBefore(logger, "微信第二步授权开始");
		PageData pd = new PageData();
		pd = this.getPageData();
		String groupId=pd.getString("groupId");
		String code=pd.getString("code");

		String boardid=pd.getString("boardid");
		String shortId=pd.getString("shortId");
		String washtype=pd.getString("washtype");
		String curBal=pd.getString("curBal");
		wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(Long.parseLong(groupId)));
		WxMpOAuth2AccessToken wxMpOAuth2AccessToken = this.wxService.oauth2getAccessToken(code);
		String openId=wxMpOAuth2AccessToken.getOpenId();
		String sign = new SimpleHash("SHA-1", boardid, shortId).toString();
		String url=String.format("%s/pay/recharge/wx_pay1.html?",ROOT_HOME_URL);
		//根据openId查询会员ID 
		url=url+"openId="+openId+"&sign="+sign+"&boardid="+boardid+"&shortId="+shortId+"&washtype="+washtype+"&groupId="+groupId+"&curBal="+curBal;
		Member member=wxApiWalletServiceService.selectMemberInfo(Long.valueOf(groupId),null,openId);
		//前端页面手机号码回显用
		if(member!=null){
			url=url +"&phone="+member.getPhone();
		}else{
			url=url +"&phone=";
		}
		logBefore(logger, "微信第二步授权结束");
		response.sendRedirect(url);
		return null;
	}

	
	
	/**
	 * @param request
	 * @param response
	 * @param tranAmt 交易金额
	 * @param phone  手机号
	 * @param sign   秘钥
	 * @param boardid  洗衣机编号
	 * @param shortId  洗衣机缩写ID
	 * @param openId   
	 * @param actualTranAmt  订单实际付款金额
	 * @param nooffertranAmt 不参与优惠后计算金额
	 * @param couponCodes    优惠券id
	 * @param bonusAmount    积分数量
	 * @param usePackage     传1表示钱包支付  微信支付为空
	 * @param payPwd    支付密码
	 * @param washtype  洗衣模式
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/xyjWxPay",method = {RequestMethod.GET,RequestMethod.POST} )
	@ResponseBody
	public Response xyjWxPay(HttpServletRequest request,HttpServletResponse response,Integer tranAmt,String phone,String sign,String boardid,String shortId,String openId,
							Integer actualTranAmt,Integer nooffertranAmt,String couponCodes,Integer bonusAmount,Integer usePackage,String payPwd,Integer washtype) throws Exception{
		logBefore(logger, "---------------------------------------------------微信完成洗衣机交易交易请求------------------------------------------");
		PageData pd = new PageData();
		pd = this.getPageData();
		System.out.println(pd);
		String notifyUrl = HOME_URL + "/api/pay/wxpayNotify";
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("支付金额", tranAmt+"");
		map.put("洗衣机编号", boardid);
		map.put("洗衣机缩写ID", shortId);
		map.put("openId不能为空", openId);
		map.put("洗衣模式", washtype+"");
		map.put("签名", sign);
		String nullParam=Response.checkNull(map);
		if (null != nullParam) {
			return Response.getError(nullParam+"不能为空");
		}
		if(tranAmt<=0){
			return Response.getError("请输入正确的消费金额");
		}
		if(usePackage!=null&&usePackage.intValue()==1&&Tools.isEmpty(payPwd)){
			return Response.getError("请输入支付密码");
		}
		if(Tools.notEmpty(couponCodes)&&actualTranAmt==null){
			return Response.getError("实付金额不能为空");
		}
		/*String signInfo = new SimpleHash("SHA-1", boardid, shortId).toString();
		if (!signInfo.equals(sign)) {
			return Response.getError("参数非法");
		}*/
		try {
			/**检查这个用户与这个门店的 是否未支付的订单**/
			wxApiWalletServiceService.checkXyjUserShopOrderStatus(phone,shortId);
			String mchCreateIp=Tools.getIpAddr(request);
			if(usePackage!=null&&usePackage.intValue()==1){ 
				Response  resultMap=wxApiWalletServiceService.updateXyjWalletPay(
        				tranAmt, mchCreateIp, phone, notifyUrl, shortId, "台卡钱包支付-洗衣机", boardid, payPwd,
                        actualTranAmt, nooffertranAmt,couponCodes,bonusAmount,ROOT_HOME_URL,washtype);
        		if(resultMap.isStatus()&&resultMap.getCode()==0){
        			TradeOffline tradeOffline=(TradeOffline)resultMap.getData_extend();
        			profitStatisService.saveOneOrderProfitCalculate(tradeOffline);
        			//memberService.insertMemberTradeDataAsyn(tradeOffline.getPayerId(),tradeOffline.getRealAmount(),tradeOffline.getBonusValue());
					memberService.insertMemberTradeData(tradeOffline.getPayerId(),tradeOffline.getRealAmount(),tradeOffline.getBonusValue());
        		}
        		return resultMap;
			}else{
				Response  resultMap=wxApiWalletServiceService.updateXyjTkPay(tranAmt, mchCreateIp, phone, notifyUrl, shortId, "微信洗衣机支付-洗衣机", boardid, openId,
						actualTranAmt, nooffertranAmt,couponCodes,bonusAmount,ROOT_HOME_URL,washtype);
				return resultMap;
			}
		} catch (ApplicationException ae) {
			logger.error(ae);
			ae.printStackTrace();
			return Response.getError(ae.errMsg);
		}
		catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return Response.getError("服务器异常");
		}
	}
}
